package com.deliveryservicesystem.app.util;

import com.deliveryservicesystem.app.util.filechooser.ExclFilter;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.table.TableModel;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * File Name: ExcelExporter.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.app.util
 * Author: Lance
 * Date: Jul 28, 2012
 * Editor:
 */
public class ExcelExporter
{

    private void fillData(TableModel model, File file) throws IOException, WriteException
    {
        WritableWorkbook workbook = Workbook.createWorkbook(file);
        WritableSheet sheet1 = workbook.createSheet("Export", 0);

        for (int i = 0; i < model.getColumnCount(); i++)
        {
            Label column = new Label(i, 0, model.getColumnName(i));
            sheet1.addCell(column);
        }
        for (int i = 0; i < model.getRowCount(); i++)
        {
            for (int j = 0; j < model.getColumnCount(); j++)
            {
                Label row = new Label(j, i + 1, model.getValueAt(i, j).toString());
                sheet1.addCell(row);
            }
        }
        workbook.write();
        workbook.close();
    }

    public void performedExport(TableModel model) throws IOException, WriteException, InterruptedException
    {
        File file = null;
        JFileChooser chooser = new JFileChooser("C:\\");
        chooser.addChoosableFileFilter(new ExclFilter());
        chooser.setAcceptAllFileFilterUsed(false);
        int option = chooser.showSaveDialog(null);
        if (option == JFileChooser.APPROVE_OPTION)
        {
            if (chooser.getSelectedFile() != null)
            {
                file = chooser.getSelectedFile();
            }
            ExcelExporter exp = new ExcelExporter();
            exp.fillData(model, file);
            Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file.toString());
            p.waitFor();
        }
    }
}